package net.zjitc.servlet.download;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Author Administrator
 * @Date 2020/5/22 10:07
 * 以附件的形式下载/读取文件
 **/
@WebServlet("/downLoad")
public class DownLoad extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /* 1、得到文件名filename: 通过获取请求参数
           2、得到文件的真实路径realPath：通过ServletContext
           3、通过字节输入流读取真实路径下的文件
           4、以附件形式下载文件，需要设置响应头
              response.setHeader("Content-Disposition", "attachment;filename="+filename);
           5、通过输入流读取文件，输出流写数据
        * */
        String filename = req.getParameter("filename");
        System.out.println(filename);
        ServletContext servletContext = req.getServletContext();
        String realPath = servletContext.getRealPath("/img/" + filename);
        FileInputStream fis = new FileInputStream(realPath);

        /* 当文件名是中文时，若要下载后的文件名跟原始文件名一致
        * 需要考虑不同浏览器对中文名编码Utf-8 是不一样的*/
        String agent=req.getHeader("User-Agent");
        filename = DownLoadUtils.getFileName(agent, filename);
        resp.setHeader("Content-Disposition", "attachment;filename=" + filename);
        ServletOutputStream outputStream = resp.getOutputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = fis.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }
        fis.close();
        outputStream.close();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
